//
//  HybridBaseViewController.swift
//  MeenoHybrid
//
//  Created by alyadan on 2016/10/16.
//  Copyright © 2016年 alyadan. All rights reserved.
//

import UIKit
import MVVM_BaseViewController
import RxCocoa
import RxSwift
import ObjectMapper

open class HybridBaseViewController: MVVM_BaseViewController {
    
    //MARK: for observerLifeCycle
    
    public lazy var viewWillAppearSubject:Observable<[Any]> = self.rx.methodInvoked(#selector(UIViewController.viewWillAppear(_:))).shareReplay(1)
    public lazy var viewWillDisappearSubject:Observable<[Any]> = self.rx.methodInvoked(#selector(UIViewController.viewWillDisappear(_:))).shareReplay(1)
    
    
    // 子类需要调用
    
    public func Hybrid_ObserveLifeCycle(hybridWebModels: [HybridWebViewModel]) {
        
        var bridges = [WebViewJavascriptBridge]()
        
        for webViewModel in hybridWebModels {
            guard let bridge = webViewModel.bridge else{
                print("error --- \(webViewModel) 's bridge is nil")
                return
            }
            
            bridges.append(bridge)
        }
        
        viewWillAppearSubject
            .bindNext {_ in
                for bridge in bridges {
                    bridge.send(HybridBaseHandler.createSendData(method:"viewWillAppear" ))
                }
            }.addDisposableTo(disposeBag)
        
        viewWillDisappearSubject
            .bindNext { _ in
                for bridge in bridges {
                    bridge.send(HybridBaseHandler.createSendData(method:"viewWillDisappear" ))
                }
            }.addDisposableTo(disposeBag)
        
    }
    
}




//MARK : base HybridVCModel 
open class HybridBaseVCModel: MVVM_BaseVCModel {
   
    
   public lazy var customData = [String: Any]()
    
    open var hybridVCDataModels:[HybridVCDataModel] {
        return []
    }
    
    public func closeMoreViewController(ids: [String], vcs: inout [UIViewController]){
        var ids = ids
        
        var matchIndex = -1
        
        for (index, id) in ids.enumerated() {
            
            for vcDataModel in self.hybridVCDataModels {
                
                if vcDataModel.pageId?.contains(id) == true, self.MVVM_modelController != nil {
                    vcs.append(self.MVVM_modelController!)
                    matchIndex = index
                    break
                }
                
            }
            
        }
        
        if matchIndex != -1 {
            ids.remove(at: matchIndex)
        }
        
        if let pvc = parentViewModel as? HybridBaseVCModel, ids.count > 0 {
            pvc.closeMoreViewController(ids: ids, vcs: &vcs)
        }
        
    }
}
